package com.jw.springboot_jw.service.impl;

import com.jw.springboot_jw.mapper.UserMapper;
import com.jw.springboot_jw.pojo.User;
import com.jw.springboot_jw.pojo.dto.UserDto;
import com.jw.springboot_jw.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 业务逻辑层
 * 实现类
 * @author wuJiaWei
 * @version 1.0
 */
@Service //标记成spring的一个bean
public class UserServiceImpl implements UserService {
    //自动装配
    @Autowired
    UserMapper userMapper;

    /**
     * 插入用户
     * @param userDto 参数
     * @return User
     */
    @Override
    public User add(UserDto userDto) {
        //创建一个User实体类对象
        User userPojo = new User();
        //属性拷贝一份,将userDto中的数据值拷贝到userPojo对象中
        BeanUtils.copyProperties(userDto, userPojo);
        //调用数据访问类的方法
        return userMapper.save(userPojo);
    }

    /**
     * 根据id查询用户
     */
    @Override
    public User get(Integer userId) {
        return userMapper.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在"));
    }

    /**
     * 修改信息
     */
    @Override
    public User update(UserDto userDto) {
        //创建一个User实体类对象
        User userPojo = new User();
        //属性拷贝一份,将userDto中的数据值拷贝到userPojo对象中
        BeanUtils.copyProperties(userDto, userPojo);
        return userMapper.save(userPojo);
    }

    @Override
    public void delete(Integer userId) {
        userMapper.deleteById(userId);
    }
}
